package net.xdclass.forum.controller;

import net.xdclass.forum.domain.Topic;
import net.xdclass.forum.domain.User;
import net.xdclass.forum.dto.PageDTO;
import net.xdclass.forum.service.CategoryService;
import net.xdclass.forum.service.TopicService;
import net.xdclass.forum.service.impl.CategoryServiceImpl;
import net.xdclass.forum.service.impl.TopicServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name = "topicServlet", urlPatterns = {"/topic"})
public class TopicServlet extends BaseServlet {

    private TopicService topicService = new TopicServiceImpl();
    private CategoryService categoryService = new CategoryServiceImpl();

    // 默认分页大小
    private static final int pageSize = 2;

    /**
     * topic分页接口
     *
     * @param req
     * @param resp
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int page = 1;
        int cId = Integer.parseInt(req.getParameter("c_id"));
        String currentPage = req.getParameter("page");
        if (currentPage != null && !"".equals(currentPage)) {
            page = Integer.parseInt(currentPage);
        }
        PageDTO<Topic> topicPageDTO = topicService.list(cId, page, pageSize);
        System.out.println(topicPageDTO.toString());
        req.getSession().setAttribute("categoryList",categoryService.list());
        req.setAttribute("topicPage", topicPageDTO);
        req.getRequestDispatcher("/index.jsp").forward(req,resp);

    }

    /**
     * 发布主题接口
     *
     * @param req
     * @param resp
     */
    public void addTopic(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute("loginUser");
        if (user == null) {
            req.setAttribute("msg", "请登录~");
            // 页面跳转
            resp.sendRedirect("/user/login.jsp");
            return;
        }
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        int cId = Integer.parseInt(req.getParameter("c_id"));
        int rows = topicService.addTopic(user, cId, title, content);

        // 发布主题成功
        resp.sendRedirect("/topic?method=list&c_id="+cId);



    }
}
